const globalData = getApp().globalData;
const Api = globalData.Api;
const wxApi = globalData.wxApi;
const getUserInfo = globalData.getUserInfo;
const setUserInfo = globalData.setUserInfo;
const SELECT_SCHOOL_PAGE = "../select-school/select-school";

let defaultValue = [2, 2];

Page({
  data: {
    value: [],
    grades: [],
    classes: [],
    pickerViewShow: false,
    user: {},
    infoType: null
  },
  onShow() {
    
  },
  onLoad( options ) {
    let type = options.type;
    this.setData({
      infoType: (type === 'bind' && type) || null
    })
    this.init();
  },
  init() {
    let self = this;
    this.userInfo = this.getUserInfo();
    console.log( this.userInfo );
    wxApi.setNavTitle('个人信息');
    // 加载年级列表
    loadGrades( grades => {
      self.setData({
        grades: grades,
        classes: loadClasses()
      })
      self.setSelectedValue(grades);
    } );
  },
  /**
   * 
   *
   * @param {*} grades
   */
  setSelectedValue(grades) {
    let userInfo = this.data.user;
    let gradeName = userInfo.gradeName;
    let gradeIndex = getGradeIndex(grades, gradeName) || 0;
    let classIndex = (userInfo.classNumber && userInfo.classNumber - 1) || 0;
    console.log( gradeIndex );
    console.log( classIndex );
    this.setData({
      value: [gradeIndex, classIndex]
    })
  },
  /**
   * 选取照片 or 照相
   *
   */
  tabkePhoto() {
    let self = this;
    console.log('take photo')
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'], 
      success: function (res) {
        console.log(res); 
        var tempFilePaths = res.tempFilePaths;
        Api.uploadImage('0', tempFilePaths[0], res => {
          self.setData({
            'user.profilePhoto': res.data
          })
        })
      }
    })
  },
  onSkip() {
    this.backToIndex();
  },
  onSexChange( e ) {
    console.log( e );
    let sexIndex = e.detail + 1;
    this.setData({
      'user.sex': sexIndex
    })
  },
  /**
   * 昵称输入变化
   * @param {Object} e
   */
  onNicknameChange( e ) {
    this.setData({
      'user.nickname': e.detail
    })
    // this.userModal.nickname = e.detail;
  },
  /**
   * 名字输入变化
   * @param {Object} e
   */
  onNameChange( e ) {
    this.setData({
      'user.name': e.detail
    })
    // this.userModal.name = e.detail;
  },
  /**
   * 选择器变化
   * @param {Object} e
   */
  onPickerChange ( e ) {
    let val = e.detail.value;
    let gradeVal = val[0];
    let gradeId = this.data.grades[ gradeVal ].id;
    let gradeName = this.data.grades[ gradeVal ].name;
    let classNumber = val[1] + 1;

    this.setData({
      value: val,
      "user.gradeId": gradeId,
      "user.classNumber": classNumber,
      "user.gradeName": gradeName
    })
  },
  /**
   * 点击年级，打开选择器
   */
  onClickGradeClass () {
    this.setData({
      pickerViewShow: !this.data.pickerViewShow
    })
  },
  /**
   * 前往 选择学校 页面
   */
  goSelectSchool () {
    
    wxApi.navigateTo(
      SELECT_SCHOOL_PAGE, 
      {
        schoolName: this.data.user.schoolName || ""
      }
    )
  },
  onSkip() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  /**
   * 更新用户信息
   *
   */
  onSaveInfo () {
    let self = this;
    let userModal
    let oldUserInfo;
    let newUserInfo;
    let infoType;
    infoType = this.data.infoType;
    oldUserInfo = this.data.user;
    userModal = this.getUserModal( oldUserInfo );
    Api.updateUserInfo( userModal, res => {
      if ( res ) {
        newUserInfo = Object.assign( oldUserInfo, res );
        self.setData({
          user: newUserInfo
        })
        setUserInfo( newUserInfo );
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        setTimeout(() => {
          if ( infoType ) {
            this.backToIndex();
          } else {
            wx.navigateBack();
          }
          
        }, 500);
      }
    } )
  },
  backToIndex() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  /**
   * 获取用户信息
   *
   * @returns userInfo
   */
  getUserInfo() {
    let self = this;
    let userInfo = null;
    userInfo = getUserInfo()
    if ( userInfo ) {
      self.setData({
        user: userInfo
      })
    }
    return userInfo;
  },
  /**
   * 获取用户数据模型
   *
   * @param {Object} user
   * @returns userModal
   */
  getUserModal(user) {
    const userModal = {
      classNumber: user.classNumber,
      gradeId: user.gradeId,
      name: user.name,
      nickname: user.nickname,
      profilePhoto: user.profilePhoto,
      schoolName: user.schoolName,
      sex: user.sex
    }
    if (user.schoolId) {
      userModal.schoolId = user.schoolId;
    }
    return userModal;
  }
})

function loadGrades(fn) {
  Api.getGrades(res => {
    console.log(res);
    fn(res);
  })
}
function loadClasses() {
  const classesLen = 50
  let classes = Object.keys(Array.apply(null,{ length: classesLen + 1 }));
  classes.shift();
  return classes;
}
function getGradeIndex(grades, gradeName) {
  for (let i = 0, grade; grade = grades[ i++ ]; ) {
    if (grade.name === gradeName) {
      return i - 1;
    } 
  }
  return 0;
}